#$Revision: 31 $
import pyglet
import cocos
from pyglet.window import key
from cocos.layer import Layer, ColorLayer
from cocos.text import Label
from cocos.actions import ScaleBy, Repeat, RotateBy, Reverse
from cocos.scenes.transitions import RotoZoomTransition, JumpZoomTransition
from cocos.scene import Scene
from cocos.menu import *
import os
import random
import characters


#Specify the resources paths for pyglet.resource
pyglet.resource.path.extend(['data', 'data/images', 'data/sounds', 'data/music', 'data/fonts'])
pyglet.resource.reindex()

#Add the data/fonts directory to the pyglet fonts directories
pyglet.font.add_directory(os.path.join(os.path.dirname(__file__), '../data/fonts'))

##################################################################################################

class PresentationLayer(Layer):
    """ Presentation layer. Very first screen of the game."""
    is_event_handler = True     #: enable pyglet's events
    
    def __init__(self):
        super(PresentationLayer, self).__init__()
        
        label = Label('Janitor vs The Birds', font_size=32, anchor_x='center', anchor_y='center')
        label.position = 400, 300
        self.add(label)
        scale = ScaleBy(1.5, duration=3)
        scale = Repeat(scale + Reverse(scale))
        rotate = RotateBy(360, duration=3)
        rotate = Repeat(rotate)
        label.do(scale)
        label.do(rotate)

        label2 = Label('Press Enter', font_size=24, anchor_x='center', anchor_y='center')
        label2.position = 400, 50
        self.add(label2)
        scale = ScaleBy(1.5, duration=0.3)
        scale = Repeat(scale + Reverse(scale))
        label2.do(scale)

    def on_key_press (self, kp, modifiers):
        """This function is called when a key is pressed.        
        'kp' is a constant indicating which key was pressed.
        'modifiers' is a bitwise or of several constants indicating which
           modifiers are active at the time of the press (ctrl, shift, capslock, etc.)        
        """
        if kp == key.ENTER:
            #cocos.director.director.replace(RotoZoomTransition(Scene(BackgroundLayer()), duration=3))
            #color_layer = ColorLayer(17,34,99,255)
            color_layer = ColorLayer(0,0,0,255)
            cocos.director.director.replace(RotoZoomTransition(Scene(CloudsLayer(), MainMenu()), duration=1))


##################################################################################################
class CloudsLayer( Layer ):
    """ Main background for the game """
    def __init__(self):
        super( CloudsLayer, self ).__init__()
        self.img = pyglet.resource.image('2buildings.png')

    def draw (self):
        self.img.blit(0,0)

##################################################################################################

class BackgroundLayer( Layer ):
    """ Main background for the game """
    is_event_handler = True     #: enable pyglet's events
    
    def __init__(self):
        super( BackgroundLayer, self ).__init__()
        #Play some music! (If AVbin is available)
        #TODO: use pyglet.media.Player to repeat the song forever (http://www.pyglet.org/doc/api/pyglet.media.Player-class.html)
        #\gasman-1.0\gamelib\soundex.py
        if pyglet.media.have_avbin:                 #If AVbin library is installed
            try:
                music = pyglet.resource.media('Weekend Amnesia.mp3')
                music.play()
            except pyglet.resource.ResourceNotFoundException:
                print "The music was not found. Enjoy the silence!"
        else:
            print "No AVbin library was found. The game will continue without music.\nPlease download AVbin from http://code.google.com/p/avbin/"
        #Background image
        self.background_img = pyglet.resource.image('escenario-etapa1.png')

        #Main character sprite
        self.janitor = characters.Janitor(x=50, y=70)
        #self.janitor.getSprite().dx = 200.0
        #Create a bird (a bat, in fact)
        self.birds = []
        for i in range(10):
            bird_posx = random.randint(0, 750)
            bird_posy = random.randint(100, 550)
            self.birds.append(characters.Bird(bird_posx, bird_posy))
            self.birds[i].speed = int(random.random() * 100)
            self.birds[i].label = Label(str( int(self.birds[i].speed) ), font_size=8, anchor_x='center', anchor_y='center', color=(0,0,0,255))
            self.birds[i].label.position = bird_posx + self.birds[i].getSpriteWidth()/2,  bird_posy + self.birds[i].getSpriteHeight() + 3
            self.add(self.birds[i].label)
        pyglet.clock.schedule_interval(self.actualizar, 1/10.0)
        self.keys_pressed = set()

    def draw (self):
        #Draw the background image
        self.background_img.blit(0,0)
        #Draw the main character sprite frame
        self.janitor.getSpriteFrame().blit(self.janitor.getX(),  self.janitor.getY())
        for b in self.birds:
            b.getSpriteFrame().blit(b.getX(), b.getY())
            b.label.position = b.getX() + b.getSpriteWidth()/2,  b.getY() + b.getSpriteHeight() + 3

        #self.janitor.getSprite().draw()

    def on_key_press (self, kp, modifiers):
        self.keys_pressed.add(kp)
        if kp == key.LEFT:
            #Update the direction and position of the main character
            self.janitor.setDirection(self.janitor.LEFT_MOVE)
            self.janitor.moveX(- 10)

        elif kp == key.RIGHT:
            #Update the direction and position of the main character
            self.janitor.setDirection(self.janitor.RIGHT_MOVE)
            self.janitor.moveX(10)
            
        #elif kp == key.SPACE:


    def on_key_release (self, kp, modifiers):
        #use discard() method instead of remove() to avoid possible KeyError exception
        self.keys_pressed.discard(kp)
        


    #Callback for pyglet.clock.schedule_interval
    def actualizar(self, dt):
        #print dt    
        #Update the position of the bird
        for b in self.birds:
            if b.getDirection() == b.LEFT_MOVE:
                #b.moveX(dt * -70 * random.random())
                b.moveX(dt * b.speed * -1)
            else:
                b.moveX(dt * b.speed)

        if key.LEFT in self.keys_pressed:
            #Update the direction and position of the main character
            self.janitor.setDirection(self.janitor.LEFT_MOVE)
            self.janitor.moveX(- 10)
        if key.RIGHT in self.keys_pressed:
            #Update the direction and position of the main character
            self.janitor.setDirection(self.janitor.RIGHT_MOVE)
            self.janitor.moveX(10)


##################################################################################################
class GameOverLayer(Layer):
    """ Game over screen """
    def __init__(self):
        super(GameOverLayer, self).__init__()
        label = Label('Game Over', font_size=72, anchor_x='center', anchor_y='center')
        label.position = 400, 300
        self.add(label)

##################################################################################################

class CreditsLayer(Layer):
    def __init__(self):
        super(CreditsLayer, self).__init__()
        label = Label('Credits', font_size=60, anchor_x='center', anchor_y='center',
                      color=(221,84,1,255), font_name='Radio Stars')
        label.position = 400, 550
        self.add(label)

        label = Label('Programming: marciano', font_size=24, anchor_x='center', anchor_y='center',
                      color=(255,255,255,255), font_name='Radio Stars')
        label.position = 400, 200
        self.add(label)

        label = Label('Art?: marciano', font_size=24, anchor_x='center', anchor_y='center',
                      color=(255,255,255,255), font_name='Radio Stars')
        label.position = 400, 150
        self.add(label)

##################################################################################################

class ScoresLayer(Layer):
    def __init__(self):
        super(ScoresLayer, self).__init__()
        label = Label('Scores', font_size=60, anchor_x='center', anchor_y='center',
                      color=(221,84,1,255), font_name='Radio Stars')
        label.position = 400, 550
        self.add(label)

        label = Label('1) marciano: 5000 points', font_size=24, anchor_x='center', anchor_y='center',
                      color=(255,255,255,255), font_name='Radio Stars')
        label.position = 400, 200
        self.add(label)

        label = Label('2) Your mom: 4999 points', font_size=24, anchor_x='center', anchor_y='center',
                      color=(255,255,255,255), font_name='Radio Stars')
        label.position = 400, 150
        self.add(label)

##################################################################################################

class HelpLayer(Layer):
    def __init__(self):
        super(HelpLayer, self).__init__()
        label = Label('Help', font_size=60, anchor_x='center', anchor_y='center',
                      color=(221,84,1,255), font_name='Radio Stars')
        label.position = 400, 550
        self.add(label)

        label = Label('* Move with arrow keys', font_size=24, anchor_x='center', anchor_y='center',
                      color=(255,255,255,255), font_name='Radio Stars')
        label.position = 400, 200
        self.add(label)

        label = Label('* Shoot with spacebar', font_size=24, anchor_x='center', anchor_y='center',
                      color=(255,255,255,255), font_name='Radio Stars')
        label.position = 400, 150
        self.add(label)

##################################################################################################        

class MainMenu(Menu):
    """ Main menu for the game """

    def __init__( self ):
        # call superclass with the title
        super( MainMenu, self ).__init__("JANITOR VS THE BIRDS")

        #Add the data/fonts directory to the pyglet fonts directories
        #pyglet.font.add_directory(os.path.join(os.path.dirname(__file__), '../data/fonts'))

        #Font attributes for the menu title
        self.font_title['font_name'] = 'African'
        self.font_title['font_size'] = 40
        self.font_title['color'] = (255,255,255,255)

        #Font attributes for the menu items
        self.font_item['font_name'] = 'Radio Stars'
        self.font_item['color'] = (144,84,48,255)

        #Font attributes for the selected menu item
        self.font_item_selected['font_name'] = 'Radio Stars'
        self.font_item_selected['color'] = (221,84,1,255)
        
        # example: menus can be vertical aligned and horizontal aligned
        self.menu_valign = CENTER
        self.menu_halign = CENTER

        #Menu items                
        items = []
        items.append( MenuItem('New Game', self.on_new_game ) )
        items.append( MenuItem('Help', self.on_help ) )
        items.append( MenuItem('Scores', self.on_scores ) )
        items.append( MenuItem('Credits', self.on_credits ) )
        items.append( MenuItem('Quit', self.on_quit ) )

        self.create_menu( items, zoom_in(), zoom_out() )

    #Callbacks
    def on_new_game(self):
        cocos.director.director.replace(RotoZoomTransition(Scene(BackgroundLayer()), duration=1))

    def on_help(self):
        color_layer = ColorLayer(17,34,99,255)
        cocos.director.director.replace(JumpZoomTransition(Scene(CloudsLayer(), HelpLayer(), BackMenu()), duration=1))

    def on_scores(self):
        color_layer = ColorLayer(17,34,99,255)
        cocos.director.director.replace(JumpZoomTransition(Scene(CloudsLayer(), ScoresLayer(), BackMenu()), duration=1))

    def on_quit(self):
        cocos.director.director.pop()

    def on_credits(self):
        color_layer = ColorLayer(17,34,99,255)
        cocos.director.director.replace(JumpZoomTransition(Scene(CloudsLayer(), CreditsLayer(), BackMenu()), duration=1))


##################################################################################################

class BackMenu(Menu):
    def __init__(self):
        super( BackMenu, self ).__init__()

        #Font attributes for the menu items
        self.font_item['font_name'] = 'Radio Stars'
        self.font_item['color'] = (144,84,48,255)

        #Font attributes for the selected menu item
        self.font_item_selected['font_name'] = 'Radio Stars'
        self.font_item_selected['color'] = (221,84,1,255)
        
        # example: menus can be vertical aligned and horizontal aligned
        self.menu_valign = BOTTOM
        self.menu_halign = CENTER

        #Menu items                
        items = []
        items.append( MenuItem('Go Back', self.on_back ) )
        self.create_menu( items, zoom_in(), zoom_out() )

    def on_back(self):
        cocos.director.director.replace(JumpZoomTransition(Scene(CloudsLayer(),MainMenu()), duration=1))

    def on_quit(self):
        self.on_back()
